<?php

header('content-type:application:json;charset=utf-8');
header('Access-Control-Allow-Origin:*');  
header('Access-Control-Allow-Methods:POST');  
header('Access-Control-Allow-Headers:x-requested-with,content-type'); 


include("lib/cls_mysql.php");
include("lib/base.class.php");
include("lib/upload.class.php");
include('lib/Uploads.php');
include('lib/config.php');




$db = new cls_mysql($cfg['host'], $cfg['user'], $cfg['pwd'],$cfg['database']);

$json_result = array('result_code'=>0,'message'=>'');

if(!$db){
	$json_result['result_code'] = 1;
	$json_result['message'] = '参数错误';
	die(json_encode($json_result));
}

$options = array(
		'rename'=>isset($_REQUEST['rename'])?$_REQUEST['rename']:'',
		'upload'=>isset($_REQUEST['upload'])?$_REQUEST['upload']:'upload',
);

$is_big_file = isset($_POST['blob_num'])?1:0;

if(!$is_big_file){
	$upload = new Upload($_FILES,$options);
	$result = $upload->run();
	
	if(!$result){
		$msg = $upload->getError();
		data_out(1,$msg);
	}
	
}
else{
	$upload = new BigUploads();
	
	$ls_dir = 'res/Bigfile';
	$name = isset($_POST['file_name'])?$_POST['file_name']:'';
	$size = isset($_POST['size'])?$_POST['size']:0;
	
	$upload->setDir($ls_dir);
	$upload->init($_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$name);
	//调用方法，返回结果
	$file_path = $upload->apiReturn();
	
	if($file_path===false){
		$arr = array(
					'name'=>$name,
					 'size'=>$size,
				);
		data_out(1,'上传部分成功',$arr);
	}
	
	$fg = explode('.',$file_path);
	$ext = end($fg);
	
	$result = array();
	$result[] = array('path'=>$file_path,
				 'name'=> $name,
				 'size'=>$size,
				 'ext'=>$ext,
				 'type'=>$upload->get_type($ext)
		);
}





$arr = array();
foreach($result as $key=>$val){
	$mark = add_record($val['name'],$val['path'],$val['size'],$val['ext']);
	
	$type = isset($val['type'])?$val['type']:'';
	$arr[] = array(
		'name'=>$val['name'],
		'mark'=>$mark,
		'size'=>$val['size'],
		'ext'=>$val['ext'],
		'url'=>get_url($mark,$val['ext'],$val['path'],$type)
	);
	
}

data_out(0,'上传成功',$arr);



function data_out($code,$msg,$data=''){
	
	$json_result = array('result_code'=>$code,'message'=>$msg,'data'=>$data);
	die(json_encode($json_result));
}

	
	
function add_record($name,$path,$size,$ext,$thumb_img=''){
	global $db,$cfg;
	$time = time();
	
	$ip = real_ip();
	$token = create_id();

	$sql = "INSERT INTO `{$cfg['table']}` (`name`,`token`,`path`,`size`,`ext`,`upload_time`,`thumb_img`,`ip`) VALUES ('{$name}','{$token}','{$path}','{$size}','{$ext}','{$time}','{$thumb_img}','{$ip}');";
	
	$db->query($sql);
	return $token;
}


function create_id(){
	global $db,$cfg;
	
	$rr = '';
	while(true){
		$time = time().'_'.rand(10000,99999);
		$rr = md5($time);
		$sql = "select id from {$cfg['table']} where token = '{$rr}' limit 1";
		$row = $db->getRow($sql);
		if(!$row){
			break;
		}
	}
	
	return $rr;
}

function get_url($id,$ext,$path,$type=''){
	global $cfg;
	$base_url = $cfg['base_url'];
	
	$url = $base_url."/".$path;
	
	if($type=='image'){
		$url = $base_url.'img.php?mark='.$id;
	}
	
	return $url;
}

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}
